package com.general.framework.cc.thread;

public class UnSafeBuyTickets {
    public static void main(String[] args) {
        BuyTickets buyTickets = new BuyTickets();
        new Thread(buyTickets, "小明").start();
        new Thread(buyTickets, "小红").start();
        new Thread(buyTickets, "小黑").start();
    }
}

class BuyTickets implements Runnable {
    private int ticketNum = 10;
    private boolean flag = true;

    // 线程不安全的做法
    @Override
    public void run() {
        while (flag) {
            buy();
        }
    }

    /*
    线程安全的做法
    @Override
    public synchronized void run() {
        while(flag){
            buy();
        }
    }
    */
    // 让线程停止
    private void stop() {
        this.flag = false;
    }

    // 买车票
    private void buy() {
        if (ticketNum <= 0) {
            System.out.println("卖完了");
            stop();
            return;
        }
        System.out.println(Thread.currentThread().getName() + "拿到" + ticketNum--);
    }
}